<!-- src/views/outbound/aaa/OutboundConfirmDialog.vue -->
<template>
  <el-dialog
    v-model="visible"
    title="确认发货单"
    width="90%"
    style="max-height: 700px;"
    :before-close="handleClose"
    @close="onClose"
  >
    <div class="confirm-dialog-container">
      <!-- 左侧商品列表 -->
      <div class="left-panel">
        <el-table
          :data="leftTableData"
          border
          style="width: 100%;"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="skuName" label="商品名称" min-width="120" />
          <el-table-column prop="code" label="商品编码" min-width="120" />
          <el-table-column prop="outCount" label="总数量" width="100" />
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button size="small" type="primary" link @click="selectRow(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 右侧仓库列表 -->
      <div class="right-panel">
        <div class="right-panel-header">
          <h3>可用库存</h3>
          <div v-if="selectedSkuName" class="selected-sku-info">
            当前选中: {{ selectedSkuName }}
          </div>
          <div v-if="selectedSkuRow" class="total-info">
            商品总数量: {{ selectedSkuRow.outCount }}
            <span v-if="totalUpCount > 0">, 已分配: {{ totalUpCount }}</span>
            <span v-if="remainingCount < 0" class="warning-text">, 超出: {{ Math.abs(remainingCount) }}</span>
          </div>
        </div>
        
        <el-table
          :data="rightTableData"
          border
          style="width: 100%; margin-top: 10px; max-height: 300px;"
          v-loading="rightLoading"
          :height="tableHeight"
          :max-height="maxTableHeight"
          :fit="true"
          :show-header="true"
          :header-cell-style="{ background: '#f5f7fa', color: '#666' }"
          :cell-style="{ padding: '12px 8px' }"
        >
          <el-table-column prop="warehouseName" label="仓库名称" min-width="120" />
          <el-table-column prop="warehouseAreaName" label="库区名称" min-width="120" />
          <el-table-column prop="locaCode" label="库位编码" min-width="100" />
          <el-table-column prop="count" label="可用数量" width="100" />
          <el-table-column label="上架数量" width="120">
            <template #default="scope">
              <el-input 
                v-model.number="scope.row.upCount" 
                type="number" 
                min="0" 
                :max="scope.row.count"
                placeholder="请输入"
                style="width: 100%;"
                @input="validateInput(scope.row)"
                :class="{ 'input-error': scope.row.upCount > scope.row.count }"
              />
            </template>
          </el-table-column>
        </el-table>
        
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { getOutboundOrderDetailsApi } from '@/api/outbound/OutboundOrderDetails';
import { getSkuListByIdApi } from '@/api/warehousingEntryUp';
import { updateOutboundOrderApi } from '@/api/outbound/outboundOrder';

const emits = defineEmits(['close', 'submit']);

// 弹窗状态
const visible = ref(false);

// 当前出库订单数据
const currentOutboundOrder = ref(null);

// 左侧表格数据
const leftTableData = ref([]);

// 右侧表格数据
const rightTableData = ref([]);

// 右侧加载状态
const rightLoading = ref(false);

// 当前选中的SKU ID
const selectedSkuId = ref(null);

// 当前选中的SKU名称
const selectedSkuName = ref('');

// 当前选中的商品行数据
const selectedSkuRow = ref(null);

// 选中的行数据
const selectedRows = ref([]);

// 表格高度计算
const tableHeight = computed(() => {
  return window.innerHeight - 240; // 根据弹窗高度动态计算
});

// 最大表格高度
const maxTableHeight = computed(() => {
  return window.innerHeight - 300; // 留出足够的空间给标题和底部按钮
});

// 计算所有上架数量的总和
const totalUpCount = computed(() => {
  return rightTableData.value.reduce((sum, item) => {
    return sum + (item.upCount || 0);
  }, 0);
});

// 计算剩余可分配数量
const remainingCount = computed(() => {
  if (!selectedSkuRow.value) return 0;
  return selectedSkuRow.value.outCount - totalUpCount.value;
});

// 打开弹窗
const open = (outboundOrder) => {
  currentOutboundOrder.value = outboundOrder;
  visible.value = true;
  fetchOrderDetails();
};

// 关闭弹窗
const handleClose = () => {
  visible.value = false;
  emits('close');
};

// 关闭时重置数据
const onClose = () => {
  selectedRows.value = [];
  currentOutboundOrder.value = null;
  selectedSkuId.value = null;
  selectedSkuName.value = '';
  selectedSkuRow.value = null;
  rightTableData.value = [];
};

// 提交处理
const handleSubmit = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个商品');
    return;
  }
  
  // 验证上架数量是否有效
  const invalidItems = rightTableData.value.filter(item => {
    return item.upCount !== undefined && item.upCount > item.count;
  });
  
  if (invalidItems.length > 0) {
    ElMessage.error('上架数量不能超过可用数量');
    return;
  }
  
  // 验证总上架数量是否超过商品总数量
  if (totalUpCount.value > selectedSkuRow.value.outCount) {
    ElMessage.error(`总上架数量(${totalUpCount.value})不能超过商品总数量(${selectedSkuRow.value.outCount})`);
    return;
  }
  
  // 验证是否至少分配了一个库存
  if (totalUpCount.value === 0) {
    ElMessage.warning('请至少为一个库存项输入上架数量');
    return;
  }
  
  // 构造提交数据
  try {
    // 获取有输入上架数量的库存项
    const selectedInventory = rightTableData.value.filter(item => item.upCount && item.upCount > 0);
    
    // 构造请求数据
    const requestData = {
      id: currentOutboundOrder.value.id, // 出库订单ID
      skuId: selectedSkuId.value, // SKU ID
      outCount: selectedSkuRow.value.outCount, // 当前选中商品的数量
      warehousingEntryUpVos: selectedInventory.map(item => ({
        id: item.id, // 库存项ID
        count: item.upCount // 上架数量
      }))
    };
    
    // 调用后端接口
    const res = await updateOutboundOrderApi(requestData);
    if (res.code === 1) {
      ElMessage.success('提交成功');
      emits('submit', requestData);
      handleClose();
    } else {
      ElMessage.error(res.msg || '提交失败');
    }
  } catch (error) {
    ElMessage.error('提交失败: ' + error.message);
  }
};

// 获取订单详情
const fetchOrderDetails = async () => {
  try {
    const res = await getOutboundOrderDetailsApi(currentOutboundOrder.value.id);
    if (res.code === 1) {
      // 转换数据格式
      leftTableData.value = res.data.map(item => ({
        ...item
      }));
    } else {
      ElMessage.error('获取订单详情失败');
    }
  } catch (error) {
    ElMessage.error('获取订单详情失败');
  }
};

// 获取SKU库存信息
const fetchSkuInventory = async (skuId, skuName, skuRow) => {
  // 如果点击的是同一个SKU，不重复请求
  if (selectedSkuId.value === skuId) {
    return;
  }
  
  selectedSkuId.value = skuId;
  selectedSkuName.value = skuName;
  selectedSkuRow.value = skuRow; // 保存当前选中的商品行数据
  rightLoading.value = true;
  
  try {
    const res = await getSkuListByIdApi(skuId);
    if (res.code === 1) {
      // 为每个库存项添加上架数量字段
      rightTableData.value = res.data.map(item => ({
        ...item,
        upCount: 0 // 初始化上架数量
      }));
    } else {
      ElMessage.error('获取库存信息失败');
      rightTableData.value = [];
    }
  } catch (error) {
    ElMessage.error('获取库存信息失败');
    rightTableData.value = [];
  } finally {
    rightLoading.value = false;
  }
};

// 处理行选择
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

// 选择单行
const selectRow = async (row) => {
  const index = selectedRows.value.findIndex(item => item.id === row.id);
  if (index === -1) {
    selectedRows.value.push(row);
  } else {
    selectedRows.value.splice(index, 1);
  }
  
  // 获取该行商品的库存信息，并传递当前行数据
  await fetchSkuInventory(row.skuId, row.skuName, row);
};

// 输入验证
const validateInput = (row) => {
  // 验证单个上架数量不超过可用数量
  if (row.upCount !== undefined && row.upCount > row.count) {
    row.upCount = row.count;
  }
  
  // 验证上架数量不为负数
  if (row.upCount < 0) {
    row.upCount = 0;
  }
  
  // 验证总上架数量不超过商品总数量（可选提示）
  if (selectedSkuRow.value && totalUpCount.value > selectedSkuRow.value.outCount) {
    // 这里可以添加视觉提示，但不强制限制单个输入
  }
};

// 暴露方法
defineExpose({
  open,
  close: handleClose
});
</script>

<style scoped>
.warning-text {
  color: #f56c6c;
  font-weight: bold;
}

.input-error {
  border-color: #f56c6c !important;
}

.total-info {
  font-size: 14px;
  color: #666;
  margin-left: 20px;
}
</style>